<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="global.Constants"%>
<html>
<head>
	<%
		String baseUrl = request.getContextPath();
	%>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript">
	    //这里的全局是为了修改之后的刷新
	    var phoneListGrid;
		var editPhonegroupWindow;
		$(document).ready(function(){
			// 全局参数
			var baseParams = {limit:<%=Constants.PAGE_SIZE %>,start : 0};
			var EXT_QUERY_TIME_OUT = 1200000;

			// 通讯录组数据源
		    var phoneListStore = new Ext.data.JsonStore({
		        url: '${pageContext.request.contextPath}/returnPhoneList.action',
		        root: 'datas',
				timeout : EXT_QUERY_TIME_OUT,
		        totalProperty: 'results',
		        fields: ['id', 'phoneid', 'name', 'phone'],
		        baseParams: baseParams,
		        autoLoad: true,
				listeners : {  
                load : function() {  
                isDetailReady = true;// 查询置换标志为已查过   
            }  
            }  
		    });
			
		   	    // 工具栏
		    var phoneListToolbar = new Ext.Toolbar({
		    	renderTo: 'phoneListToolBarDiv',
		    	items: [
					new Ext.Button({
					    id: 'phoneList-add-button',
					    text: '添加',
						iconCls: 'note_add'
						//disabled:true
					}),
					new Ext.Button({
					    id: 'phoneList-update-button',
					    text: '编辑',
						iconCls: 'note_edit'
					}),
					new Ext.Button({
					    id: 'phoneList-delete-button',
					    text: '删除',
						iconCls: 'note_delete'
					}),
					'-',
		            new Ext.ux.form.SearchField({
		                store: phoneListStore,
		                width: 320,
		                paramName: 'name',
		                emptyText: '请输通讯录组名...',
		                style: 'margin-left: 10px;'
		            })
				]
			});

			// 用户数据表格
			var sm = new Ext.grid.CheckboxSelectionModel();
			phoneListGrid = new Ext.grid.GridPanel({
				id: 'phoneListGrid',
				renderTo: 'phoneListGridDiv',
				border: false,
				stateful: true,
			    autoScroll: 'auto',
		        store: phoneListStore,
		        loadMask: true,
		        cm: new Ext.grid.ColumnModel({
		            defaults: {
		                width: 100,
		                sortable: true
		            },
			        columns: [
						sm,
						new Ext.grid.RowNumberer({header:'№',width:50}),
						{id:'id',header: '用户ID', width: 100, hidden: true, sortable: true, dataIndex: 'id'},
			            {id:'name',header: '通讯录组', width: 100, sortable: true, dataIndex: 'name'},
			            {id:'phone',header: '电话', width: 200, sortable: true, dataIndex: 'phone'}
					]
		        }),
		        sm: sm,
		        columnLines: true,
		        bbar: new Ext.PagingToolbar({
					pageSize: <%=Constants.PAGE_SIZE %>,
					store: phoneListStore,
					displayInfo: true,
					displayMsg: Anynote.PAGINGTOOLBAR_DISPLAYMSG,
					emptyMsg: Anynote.PAGINGTOOLBAR_EMPTYMSG,
					doLoad: function(start){
						baseParams.start = start;
						this.store.load({params: baseParams});
					}
		        })
		    });
			// 设置Grid高度和宽度
			Anynote.resizeGridTo("phoneListGrid", 0, 56);
			
			// 添加按钮
			$("#phoneList-add-button").click(function(){
		     	// 通讯录组
		        var phoneStore = new Ext.data.JsonStore({ 
		            fields : ['id', 'name', 'id_name'],  
		            root:'datas',
		            url:'${pageContext.request.contextPath}/returnPhonelistName.action',
		            autoLoad: true
		        });
        
				// 新增通讯录Form
				var addPhoneFormPanel = new Ext.FormPanel({
					id: 'addPhoneFormPanel',
			        labelWidth: 60,
			        buttonAlign: 'center',
			        border: false,
			        bodyStyle: 'padding:10px;text-align:left;background-color:transparent;',
			        url: '',
		            items:[{// 通讯录组名
			                xtype:'combo',
			                hiddenName: 'address',
			                fieldLabel: '通讯组',
			                store: phoneStore,
			                mode : 'local',
			                triggerAction: "all",
			                valueField: 'id_name',
			                displayField: 'name',
			                allowBlank:false,
			                editable: false,
			                anchor:'98%',
			                listeners:{
			                blur:function(n){
			                var va = n.getValue().split(" ")[1];
			                Ext.Ajax.request({
	                        url:  '${pageContext.request.contextPath}/proving_provingOnly.action',
		                    params:{val:va,filed:'name',table:'t_s_phonelist'},
		                    success: function(res){
		                      var isPorv = res.responseText;
		                      if(isPorv == 1){
		                        n.setValue('');
		                        Ext.Msg.alert('错误', '该通讯组录名已经存在,请重新选择!!!');
		                        }
			                }
			                })
			                }
			                }
		                },{// 电话
			               xtype:'textarea',
			               id:'phone',
			               name:'phone',
			               fieldLabel:'电话',
			               anchor:'98%',
			               allowBlank:false,
			               maxLength: 200
			           }],
			        buttons: [{
	                    text:'提交',
	                    handler: function(){
				        	var form = addPhoneFormPanel.getForm();
						    if(form.isValid()){
						    	// 发送请求
								Anynote.ajaxRequest({
									baseUrl: '<%=baseUrl %>',
									baseParams: form.getValues(),
									action: '${pageContext.request.contextPath}/insertPhoneInfor.action',
									callback: function(jsonResult){
										phoneListGrid.getStore().reload();
										addPhoneWindow.close();
									},
									showWaiting: true,
									failureMsg: '保存失败.'
								});
							}
	                	}
	                },{
	                    text: '重置',
	                    handler: function(){
	                		addPhoneFormPanel.getForm().reset();
	                    }
	                }]
			    });
				// 用户注册窗口
				var addPhoneWindow = new Ext.Window({
					title: '添加通讯录',
					width: 300,
					height: 220,
					modal: true,
					maximizable: false,
					resizable: false,
					iconCls: 'phone_add',
					layout:'fit',
					plain: true,
					items: [addPhoneFormPanel]
				}).show();
			});

			// 启用编辑
			$("#phoneList-update-button").click(function(){
				// 启用
				submit("update");
			});

			// 删除按钮
			$("#phoneList-delete-button").click(function(){
				// 提交
				submit("delete");
			});

			// 提交
			function submit(type){
				var msg = "";
				var status = 0;
				if(type=="delete"){
				    status = 1;
					msg = "确定要删除这条记录吗？";
				}else if(type=="update"){
				    status = 2;
				}
				var records = phoneListGrid.getSelectionModel().getSelections();
				
				if(records.length < 1){
					 Ext.Msg.alert("提示", "请至少选择一条数据.");
				}else{
					   //如果点击的是删除
					   if(status == 1){
					      Ext.Msg.confirm("警告", msg, function(btn){
						  if(btn=="yes"){
							var addressIds = "";
							for(var i=0;i<records.length;i++){
								addressIds = addressIds + records[i].get("id") + ",";
							}
							// 发送请求
							Anynote.ajaxRequest({
								baseUrl: '<%=baseUrl %>',
								baseParams: {addressIds:addressIds, status:status},
								action: '${pageContext.request.contextPath}/deletePhoneListInfor.action',
								callback: function(jsonResult){
									phoneListGrid.getStore().reload();
								},
								showWaiting: true,
								failureMsg: '保存失败.'
							});
						   }
					     });
					   //如果点击的是编辑
					   }else if(status == 2){
					        var addressIds = "";
						    addressIds = records[0].get("id");
					        //只能一条一条的编辑，不能多个一起编辑
					        if(records.length == 1){
						        editPhonegroupWindow = new Ext.Window({
								title: '编辑通讯录组',
								width: 350,
								height: 220,
								modal: true,
			
								maximizable: false,
								resizable: false,
								layout:'fit',
								iconCls: 'note_edit',
								plain: true,
								autoLoad:{url:'${pageContext.request.contextPath}/page/bussmodule/phonegroup/editAddress.jsp?addressId='+addressIds,scripts:true,nocache:true},
								listeners: {
									close: function(){
									}
								}
								});
								editPhonegroupWindow.show();
					        }else{
					            Ext.Msg.alert("提示", "只能选择一条数据.");
					        }
					   }
					}
			}
});

	</script>
</head>
<body>
<div id="phoneListDiv">
	<div id="phoneListToolBarDiv"></div>
	<div id="phoneListGridDiv" style="width:100%;height:100%;"></div>
</div>
</body>
</html>
